<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单信息统计系统 - 数据仪表板</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .main-content {
            padding: 30px 15px;
        }
        
        .stats-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(0,0,0,0.1);
        }
        
        .chart-container {
            height: 400px;
            width: 100%;
        }
        
        .recommendation-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border-left: 4px solid #667eea;
        }
        
        .recommendation-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 3px solid #28a745;
        }
        
        .search-section {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        
        .btn-logout {
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: white;
            transition: all 0.3s ease;
        }
        
        .btn-logout:hover {
            background: rgba(255,255,255,0.3);
            color: white;
        }
        
        .section-title {
            color: #333;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }
        
        .metric-value {
            font-size: 2.5rem;
            font-weight: 700;
            color: #667eea;
        }
        
        .metric-label {
            color: #6c757d;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="fas fa-chart-line me-2"></i>订单统计系统
            </a>
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    <i class="fas fa-user me-1"></i>欢迎, ${sessionScope.username}
                </span>
                <a class="btn btn-logout" href="${pageContext.request.contextPath}/logout">
                    <i class="fas fa-sign-out-alt me-1"></i>退出
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid main-content">
        <!-- 统计概览 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="metric-value" id="validOrderCount">0</div>
                    <div class="metric-label">有效订单</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="metric-value" id="invalidOrderCount">0</div>
                    <div class="metric-label">无效订单</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="metric-value" id="totalCategories">0</div>
                    <div class="metric-label">订单类别</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="metric-value" id="totalProducts">0</div>
                    <div class="metric-label">产品数量</div>
                </div>
            </div>
        </div>

        <!-- 图表展示 -->
        <div class="row">
            <!-- 有效/无效订单饼图 -->
            <div class="col-md-6">
                <div class="stats-card">
                    <h5 class="section-title">
                        <i class="fas fa-pie-chart me-2"></i>订单有效性分布
                    </h5>
                    <div id="validInvalidChart" class="chart-container"></div>
                </div>
            </div>
            
            <!-- 订单类别柱状图 -->
            <div class="col-md-6">
                <div class="stats-card">
                    <h5 class="section-title">
                        <i class="fas fa-bar-chart me-2"></i>各类别订单数量
                    </h5>
                    <div id="categoryChart" class="chart-container"></div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 类别有效性统计 -->
            <div class="col-md-8">
                <div class="stats-card">
                    <h5 class="section-title">
                        <i class="fas fa-chart-area me-2"></i>各类别有效/无效订单统计
                    </h5>
                    <div id="categoryValidChart" class="chart-container"></div>
                </div>
            </div>
            
            <!-- 热门产品TOP3 -->
            <div class="col-md-4">
                <div class="stats-card">
                    <h5 class="section-title">
                        <i class="fas fa-trophy me-2"></i>热门产品TOP3
                    </h5>
                    <div id="topProductsList">
                        <!-- 将通过JavaScript动态填充 -->
                    </div>
                </div>
            </div>
        </div>

        <!-- 推荐系统 -->
        <div class="row">
            <!-- 个性化推荐 -->
            <div class="col-md-4">
                <div class="recommendation-card">
                    <h5 class="section-title">
                        <i class="fas fa-user-tag me-2"></i>基于用户推荐(User-Based CF)
                    </h5>
                    <div id="userBasedRecommendations">
                        <!-- 将通过JavaScript动态填充 -->
                    </div>
                </div>
            </div>
            
            <!-- 基于物品推荐 -->
            <div class="col-md-4">
                <div class="recommendation-card">
                    <h5 class="section-title">
                        <i class="fas fa-boxes me-2"></i>基于物品推荐(Item-Based CF)
                    </h5>
                    <div id="itemBasedRecommendations">
                        <!-- 将通过JavaScript动态填充 -->
                    </div>
                </div>
            </div>
            
            <!-- 离线推荐 -->
            <div class="col-md-4">
                <div class="recommendation-card">
                    <h5 class="section-title">
                        <i class="fas fa-fire me-2"></i>热门推荐(离线推荐)
                    </h5>
                    <div id="offlineRecommendations">
                        <!-- 将通过JavaScript动态填充 -->
                    </div>
                </div>
            </div>
        </div>

        <!-- 搜索功能 -->
        <div class="row">
            <div class="col-12">
                <div class="search-section">
                    <h5 class="section-title">
                        <i class="fas fa-search me-2"></i>类别搜索与相似推荐
                    </h5>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="input-group">
                                <input type="text" class="form-control" id="searchInput" 
                                       placeholder="请输入要搜索的类别名称...">
                                <button class="btn btn-primary" onclick="searchCategory()">
                                    <i class="fas fa-search"></i> 搜索
                                </button>
                            </div>
                        </div>
                    </div>
                    <div id="searchResults" class="mt-3"></div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 页面数据
        const statsData = <c:choose>
            <c:when test="${statsJson != null}">
                ${statsJson}
            </c:when>
            <c:otherwise>
                {}
            </c:otherwise>
        </c:choose>;
        
        const recommendationsData = <c:choose>
            <c:when test="${recommendationsJson != null}">
                ${recommendationsJson}
            </c:when>
            <c:otherwise>
                {}
            </c:otherwise>
        </c:choose>;
        
        // 初始化图表
        document.addEventListener('DOMContentLoaded', function() {
            initializeCharts();
            updateMetrics();
            renderRecommendations();
            // 每30秒刷新一次数据
            setInterval(refreshData, 30000);
        });
        
        function initializeCharts() {
            // 有效/无效订单饼图
            const validInvalidChart = echarts.init(document.getElementById('validInvalidChart'));
            const validInvalidOption = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [{
                    name: '订单状态',
                    type: 'pie',
                    radius: '50%',
                    data: statsData.validInvalidStats || [
                        {value: 0, name: '有效订单'},
                        {value: 0, name: '无效订单'}
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };
            validInvalidChart.setOption(validInvalidOption);
            
            // 订单类别柱状图
            const categoryChart = echarts.init(document.getElementById('categoryChart'));
            const categoryData = statsData.categoryStats || [];
            const categoryOption = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: categoryData.map(item => item.name),
                    axisTick: {
                        alignWithLabel: true
                    }
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    name: '订单数量',
                    type: 'bar',
                    barWidth: '60%',
                    data: categoryData.map(item => item.value),
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {offset: 0, color: '#667eea'},
                            {offset: 1, color: '#764ba2'}
                        ])
                    }
                }]
            };
            categoryChart.setOption(categoryOption);
            
            // 类别有效性统计图
            const categoryValidChart = echarts.init(document.getElementById('categoryValidChart'));
            const categoryValidData = statsData.categoryValidStats || [];
            
            // 处理数据格式
            const categories = [...new Set(categoryValidData.map(item => item.category))];
            const validData = categories.map(cat => {
                const item = categoryValidData.find(d => d.category === cat && d.type === '有效');
                return item ? item.value : 0;
            });
            const invalidData = categories.map(cat => {
                const item = categoryValidData.find(d => d.category === cat && d.type === '无效');
                return item ? item.value : 0;
            });
            
            const categoryValidOption = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    data: ['有效订单', '无效订单']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: categories
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '有效订单',
                        type: 'bar',
                        stack: '总量',
                        data: validData,
                        itemStyle: {
                            color: '#28a745'
                        }
                    },
                    {
                        name: '无效订单',
                        type: 'bar',
                        stack: '总量',
                        data: invalidData,
                        itemStyle: {
                            color: '#dc3545'
                        }
                    }
                ]
            };
            categoryValidChart.setOption(categoryValidOption);
            
            // 响应式处理
            window.addEventListener('resize', function () {
                validInvalidChart.resize();
                categoryChart.resize();
                categoryValidChart.resize();
            });
        }
        
        function updateMetrics() {
            const validData = statsData.validInvalidStats || [];
            const validCount = validData.find(item => item.name === '有效订单');
            const invalidCount = validData.find(item => item.name === '无效订单');
            
            document.getElementById('validOrderCount').textContent = validCount ? validCount.value : 0;
            document.getElementById('invalidOrderCount').textContent = invalidCount ? invalidCount.value : 0;
            document.getElementById('totalCategories').textContent = (statsData.categoryStats || []).length;
            document.getElementById('totalProducts').textContent = (statsData.topProducts || []).length;
        }
        
        function renderRecommendations() {
            // 渲染热门产品TOP3
            const topProductsList = document.getElementById('topProductsList');
            const topProducts = statsData.topProducts || [];
            if (topProducts.length > 0) {
                topProductsList.innerHTML = topProducts.map(function(product, index) {
                    return '<div class="recommendation-item">' +
                           '<div class="d-flex justify-content-between align-items-center">' +
                           '<span><strong>#' + (index + 1) + '</strong> ' + product.name + '</span>' +
                           '<span class="badge bg-primary">' + product.count + '</span>' +
                           '</div>' +
                           '</div>';
                }).join('');
            } else {
                topProductsList.innerHTML = '<p class="text-muted">暂无数据</p>';
            }
            
            // 渲染基于用户的推荐
            const userBasedRecs = document.getElementById('userBasedRecommendations');
            const userBasedData = recommendationsData.userBased || [];
            if (userBasedData.length > 0) {
                userBasedRecs.innerHTML = userBasedData.map(function(rec) {
                    return '<div class="recommendation-item">' +
                           '<div class="d-flex justify-content-between">' +
                           '<span>' + (rec.product || rec.name || '推荐商品') + '</span>' +
                           '<small class="text-muted">评分: ' + (rec.score || rec.count || '4.0') + '</small>' +
                           '</div>' +
                           '</div>';
                }).join('');
            } else {
                userBasedRecs.innerHTML = '<p class="text-muted">暂无推荐数据</p>';
            }
            
            // 渲染基于物品的推荐
            const itemBasedRecs = document.getElementById('itemBasedRecommendations');
            const itemBasedData = recommendationsData.itemBased || [];
            if (itemBasedData.length > 0) {
                itemBasedRecs.innerHTML = itemBasedData.map(function(rec) {
                    return '<div class="recommendation-item">' +
                           '<div class="d-flex justify-content-between">' +
                           '<span>' + (rec.product || rec.name || '推荐商品') + '</span>' +
                           '<small class="text-muted">相似度: ' + (rec.similarity || '0.85') + '</small>' +
                           '</div>' +
                           '</div>';
                }).join('');
            } else {
                itemBasedRecs.innerHTML = '<p class="text-muted">暂无推荐数据</p>';
            }
            
            // 渲染离线推荐
            const offlineRecs = document.getElementById('offlineRecommendations');
            const offlineData = recommendationsData.offline || [];
            if (offlineData.length > 0) {
                offlineRecs.innerHTML = offlineData.map(function(rec) {
                    return '<div class="recommendation-item">' +
                           '<div class="d-flex justify-content-between">' +
                           '<span>' + (rec.name || rec.itemId || '热门类别') + '</span>' +
                           '<small class="text-muted">热度: ' + (rec.count || rec.score || '100') + '</small>' +
                           '</div>' +
                           '</div>';
                }).join('');
            } else {
                offlineRecs.innerHTML = '<p class="text-muted">暂无推荐数据</p>';
            }
        }
        
        function refreshData() {
            // 这里可以添加AJAX调用来刷新数据
            console.log('Refreshing data...');
            // location.reload(); // 简单的页面刷新，实际应用中应该使用AJAX
        }
        
        function searchCategory() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            if (!searchTerm) {
                alert('请输入搜索关键词');
                return;
            }
            
            // 显示加载状态
            document.getElementById('searchResults').innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin"></i> 搜索中...</div>';
            
            // 调用后端搜索API
            fetch('/dashboard', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=search&searchTerm=' + encodeURIComponent(searchTerm)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('搜索请求失败');
                }
                return response.json();
            })
            .then(data => {
                displaySearchResults(searchTerm, data);
            })
            .catch(error => {
                console.error('搜索错误:', error);
                document.getElementById('searchResults').innerHTML = '<div class="alert alert-danger">搜索失败，请重试</div>';
            });
        }
        
        function displaySearchResults(searchTerm, data) {
            const matched = data.matched || {};
            const similar = data.similar || [];
            const products = data.products || [];
            
            let resultsHtml = '<div class="row">';
            
            // 搜索结果部分
            resultsHtml += '<div class="col-md-6">';
            resultsHtml += '<h6>搜索结果: "' + searchTerm + '"</h6>';
            
            if (matched.found) {
                resultsHtml += '<div class="recommendation-item">';
                resultsHtml += '<strong>' + matched.name + '</strong>';
                resultsHtml += '<p class="mb-1">类别统计信息</p>';
                resultsHtml += '<small class="text-muted">有效订单: ' + matched.validCount + ' | 无效订单: ' + matched.invalidCount + ' | 总订单: ' + matched.totalCount + '</small>';
                resultsHtml += '</div>';
                
                // 显示该类别的热门产品
                if (products.length > 0) {
                    resultsHtml += '<h6 class="mt-3">该类别热门产品 TOP' + products.length + '</h6>';
                    products.forEach(function(product, index) {
                        resultsHtml += '<div class="recommendation-item">';
                        resultsHtml += '<div class="d-flex justify-content-between">';
                        resultsHtml += '<span>#' + (index + 1) + ' ' + product.name + '</span>';
                        resultsHtml += '<small class="text-muted">订单数: ' + product.count + '</small>';
                        resultsHtml += '</div>';
                        resultsHtml += '</div>';
                    });
                }
            } else {
                resultsHtml += '<div class="alert alert-warning">';
                resultsHtml += '<strong>未找到匹配的类别</strong>';
                resultsHtml += '<p class="mb-0">没有找到包含 "' + searchTerm + '" 的类别</p>';
                resultsHtml += '</div>';
            }
            
            resultsHtml += '</div>';
            
            // 相似类别推荐部分
            resultsHtml += '<div class="col-md-6">';
            resultsHtml += '<h6>相似类别推荐 TOP' + similar.length + '</h6>';
            
            if (similar.length > 0) {
                similar.forEach(function(category) {
                    resultsHtml += '<div class="recommendation-item">';
                    resultsHtml += '<div class="d-flex justify-content-between">';
                    resultsHtml += '<span>' + category.name + '</span>';
                    resultsHtml += '<small class="text-muted">相似度: ' + category.similarity + ' | 订单数: ' + category.count + '</small>';
                    resultsHtml += '</div>';
                    resultsHtml += '</div>';
                });
            } else {
                resultsHtml += '<div class="alert alert-info">';
                resultsHtml += '<p class="mb-0">暂无相似类别推荐</p>';
                resultsHtml += '</div>';
            }
            
            resultsHtml += '</div>';
            resultsHtml += '</div>';
            
            document.getElementById('searchResults').innerHTML = resultsHtml;
        }
        
        // 回车搜索
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchCategory();
            }
        });
    </script>
</body>
</html> 